import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Divider, Drawer, message, Modal, Select, Tag } from 'antd';
import type { SorterResult } from 'antd/es/table/interface';

import React, { useRef, useState } from 'react';
import type { Gender, TableListItem } from './data';
import { queryMemberUserList, queryUserDetail } from './service';
import UserDetail from './components/UserDetail';
import { genderEnumValue, GenderOptions, GenderParse } from '@/pages/Member/utils';

const TableList: React.FC = () => {
  const [detailModalVisible, handledetailModalVisible] = useState<boolean>(false);
  const [detailItemId, setDetailItemId] = useState<string | null>(null);
  const [sorter, setSorter] = useState<string>('');
  const actionRef = useRef<ActionType>();

  const handleRemove = async () => {
    const hide = message.loading('正在删除');
    try {
      hide();
      message.success('删除成功');
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      return false;
    }
  };

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '名称',
            dataIndex: 'nickname',
      render: (_, record) => <Tag>{record.nickname}</Tag>,
    },
    {
      title: '手机号',
            dataIndex: 'mobile',
      render: (_, record) => <Tag>{record.mobile || '未知'}</Tag>,
    },
    // {
    //   title: '身份证号',
    //   // @ts-ignore
    //   dataIndex: 'idCardNo',
    //   render: (_, record) => <Tag>{ record.idCardNo || '未知' }</Tag>,
    // },
    {
      title: '性别',
      dataIndex: 'gender',
      hideInSearch: false,
      render: (_, record) => {
        const gender: Gender = GenderParse.parse(record.gender);
        return <Tag color={gender.color}>{gender.name}</Tag>;
      },
      valueEnum: genderEnumValue()
      // renderFormItem: (_, { onChange }) => (
      //   <Select defaultValue="0">
      //     {GenderOptions.map((item) => (
      //       <Select.Option key={item.id} value={item.id}>
      //         {item.name}
      //       </Select.Option>
      //     ))}
      //   </Select>
      // ),
    },
    {
      title: '操作',
            dataIndex: 'options',
      hideInSearch: true,
      render: (_, record) => {
        const onShowDetail = () => {
          const { id } = record;
          setDetailItemId(id);
          handledetailModalVisible(true);
        };

        const onClickRemove = () => {
          Modal.confirm({
            title: `删除 ${record.nickname}`,
            content: (
              <>
                <Divider />
                <p>确认要删除</p>
                <span style={{ fontWeight: 'bolder' }}>{record.nickname}</span>&nbsp;&nbsp;?
              </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await handleRemove();
            },
          });
        };

        return (
          <div>
            <a onClick={onShowDetail}>详情</a>
            <Divider type="vertical" />
            <a onClick={onClickRemove}>删除</a>
          </div>
        );
      },
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<TableListItem>
        headerTitle="小程序用户列表"
        actionRef={actionRef}
        rowKey="id"
        scroll={{ x: true }}
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<TableListItem>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        params={{
          sorter,
        }}
        toolBarRender={() => []}
        tableAlertRender={() => false}
        rowSelection={false}
        request={(params = {}) => {
          const { current: page, pageSize, ...filter } = params;
          return queryMemberUserList({ page, pageSize, ...filter });
        }}
        columns={columns}
      />
      <Drawer
        visible={!!detailItemId && detailModalVisible}
        onClose={() => handledetailModalVisible(false)}
        width="30%"
      >
        {!!detailItemId && detailModalVisible && (
          <UserDetail id={detailItemId} request={(id) => queryUserDetail({ id })} />
        )}
      </Drawer>
    </PageHeaderWrapper>
  );
};

export default TableList;
